<?php
namespace app\services;

use app\services\ExcelService;
use app\utils\Functions as F;

class DaddyCallService extends BaseService {

	public function getImportData() {
		$fileInfo = $this->uploadExcel();
		return $this->addImportData($fileInfo);
	}

    public function addImportData($fileInfo) {
        if (is_array($fileInfo)) {
            $fileInfo = $fileInfo[0];
            $serv = new ExcelService();
            $datas = $serv->readXlsx($fileInfo['savepath'].$fileInfo['savename']); 
            $categorys = $this->getAll('AdspaceCategory', ['ad_network_id' => 2], 'name');
            $categorys['论坛社区'] = $categorys['社区'];
            $categorys['社区论坛'] = $categorys['社区'];
            $categorys['it数码'] = $categorys['IT数码'];
            $categorys['娱乐八卦'] = $categorys['休闲娱乐'];
            $ads = $this->getAll('Adspace', ['ad_network_id' => 2], 'ad_network_adspace_id');
            $inSerts = [];
            foreach ($datas as $data) {
                if ($data['流量类型'] != "PC网页")  continue;
                if (isset($ads[$data['推广位PID']]))  continue;
                $Ad=[];
                $Ad = $this->getAdInfo($data, $categorys);
                $inSerts[] = " ('${Ad['media_id']}',
                               '${Ad['ad_network_adspace_id']}',
                               '${Ad['category_id']}',
                               '${Ad['name']}',
                               '${Ad['page_url']}',
                               '${Ad['width']}',
                               '${Ad['height']}',
                               '${Ad['position']}',
                               '${Ad['ad_network_id']}',
                               '${Ad['format_list']}',
                               '${Ad['base_price']}')";
                unset($Ad);
            }
            if(count($inSerts)) {
                $inSerts = array_chunk($inSerts, 1000, true);
                foreach ($inSerts as $newS) {
                    $sql = 'insert into {{%adspace}} (media_id, ad_network_adspace_id, category_id, name, page_url, 
                        width, height, position, ad_network_id, format_list, base_price) values '.implode(',', $newS).';';
                    $this->executeSql($sql);
                }
            }
            $fileInfo['size'] = number_format($fileInfo['size']/1024, 2).'k';
        }
        return $fileInfo;       
    }

    public function getAdInfo($data, $categorys) {
        $NewAd=[];
        $NewAd['media_id'] = $data['网站名称'];
        $NewAd['ad_network_adspace_id'] = $data['推广位PID'];
        if(isset($categorys[$data['网站类目']])) {
            $NewAd['category_id'] = $categorys[$data['网站类目']]['category_id'];
        } else  {
            $NewAd['category_id'] = 0;
        }
        $NewAd['name'] = $data['网站名称'].'_'.$data['推广位名称'];
        $NewAd['page_url'] = $data['网站域名'];
        $size = explode('x', $data['投放尺寸']);
        $NewAd['width'] = $size[0];
        $NewAd['height'] = $size[1];
        $NewAd['position'] = 4;
        $data['屏数'] == '未知' && $NewAd['position'] = 0;
        $data['屏数'] == '首屏' && $NewAd['position'] = 1;
        $data['屏数'] == '二屏' && $NewAd['position'] = 2;
        $data['屏数'] == '三屏' && $NewAd['position'] = 3;
        $NewAd['ad_network_id'] = 2;
        $NewAd['format_list'] = "1,2,3";
        $NewAd['base_price'] = '0';
        return $NewAd;        
    }

	public function getRef($result) {
        if (is_array($result)) {
            $table[] = [
                'name' => $result['name'],
                'size' => $result['size'],
                'date' => date('Y/m/d H:i:s'),
                'judgeInfo' => '符合需求',
                'updater' =>  F::get_client_ip(),
            ];
        }
        return ['table' => $table];
    }

    public function getCreativeInfo() {
        $creativeId = $this->I('creative');
        $ad_network_id = $this->I('content_channel_radio');
        switch ($ad_network_id) {
            case '1':
                $result = $this->getVamCreativeInfo($creativeId);
                break;
            case '2':
                $result = $this->getTanxCreativeInfo($creativeId);
                break;
            default:
                $result = "查询失败";
                break;
        }
        return ['data' => $result];
    }

	public function getVamCreativeInfo($creativeId) {
        $where = ['creative_id' => $creativeId, 'ad_network_id' => 1];
        $creativeInfo = $this->getOne('CreativeSsp', $where);
        $msg = "查询失败";
        if (!$creativeInfo) return $msg;
        switch ($creativeInfo['ssp_audit_status']) {
            case '0':
                $msg = "创意待审核";
                break;
            case '1':
                $msg = "创意审核中";
                break;
            case '2':
                $msg = "创意审核通过";
                break;
            case '3':
                $msg = "创意被拒绝";
                break;
            default:
                break;
        }
        return $msg;
    }

    public function getTanxCreativeInfo($creativeId) {
        $serv = new TanxService(); 
        $result = $serv->getTanxCreativeInfo($creativeId);
        $msg = "查询失败";
        if(!is_array($result)) return $msg;
        $result = $result['tanx_creative_get_response'];
        if($result['is_ok']) {
            if ($result['result']['status'] == 'PASS') {
                $msg = "创意审核通过";
                $result['result']['level'] == 1 && $msg .= ",  创意级别：一级创意";
                $result['result']['level'] == 99 && $msg .= ", 创意级别：普通创意";
            }
            if ($result['result']['status'] == 'REFUSE') { 
                $msg = "创意被拒绝";
                $msg = $msg.", 拒绝原因：".$result['result']['refuse_cause'];
            }
            $result['result']['status'] == 'WAITING' && $msg = "创意待审核";  
        }
        return $msg;
    }

    public function saveImportData() {
        $solutionId = $this->I('solution');
        $cost = $this->I('cost');
        $show = $this->I('show');
        $click = $this->I('click');
        $time = $this->I('date');   //"2016-05-01"
        $brand = $this->I('brand');

        $solutionInfo = $this->getOne('Solution', ['id' => $solutionId]);
        if (!$solutionInfo) return $this->NG('该策略不存在！');
        if ($solutionInfo['advertiser_id'] != $brand) return $this->NG('策略和品牌不匹配！');
        $campaign = $this->getOne('Campaign', ['id' => $solutionInfo['campaign_id']]);
        $label = $this->getOne('CampaignLabel', ['id' => $campaign['label_id']]);
        $advertiser = $this->getOne('Advertiser', ['id' => $brand]);

        $sql = " select MIN(id) mid from vam_rpt_sumadbyday where id <= 0";
        $mid = $this->queryOne($sql);
        !$mid['mid'] && $data['id'] = -1;
        $mid['mid'] && $data['id'] = $mid['mid'] - 1;
        $data['solutionid']  = $solutionId;
        $data['creativeuuid']  = '0';
        $data['exchangeid'] = '1';
        $data['campaign_id'] = $campaign['id'];
        $data['seller_name'] = 'vamaker';
        $data['adspace_name'] = '未知';
        $data['solution_name'] = $solutionInfo['name'];
        $data['advertiser_id'] = $brand;
        $data['campaign_name'] = $campaign['name'];
        $data['advertiser_name'] = $advertiser['name'];
        $data['creative_name'] = '未知';
        $data['shows'] = $show;
        $data['origin_cost'] = $cost;
        $data['cost'] = $cost;
        $data['clicks'] = $click;
        $data['logdate'] = $time;
        $data['logdate_id'] = date('Ymd', strtotime($time));
        $data['quarter'] = intval((date('n', strtotime($time))+2)/3);
        $data['week'] = date('W', strtotime($time));
        $data['month'] = date('n', strtotime($time));
        $data['flag'] = '1';
        $data['dbFlag']  = '2015';
        $data['creator'] = '3';
        $data['creator_name']  = 'operator';
        $data['label_id'] =  $label['id'];
        $data['campaign_label_name'] = $label['name'];
        $data['created'] = date('Y-m-d H:i:s');
        $data['modified'] = date('Y-m-d H:i:s');

        $where = "solutionid = $solutionId and logdate = '". $time ."' and advertiser_id = $brand and id < 0";
        $oldData = $this->getOne('RptSumadbyday', $where);
        if ($oldData) {
            unset($data['id']);
            $sql = "update {{%rpt_sumadbyday}} set ";
            $sqlData = [];
            foreach ($data as $key => $value) {
                $sqlData[] = " $key = ".'"'.$value.'"';
            }
            $sql .= implode(', ', $sqlData) . " where ".$where;
            $this->executeSql($sql);
        } else {
            $sql = "insert into {{%rpt_sumadbyday}} ";
            $keys = array_keys($data);
            $values = array_values($data);
            $sql .= '( '. implode(',', $keys). " ) values ( '". implode("' , '", $values). "')";
            $this->executeSql($sql);
        }
        $msg = '数据保存成功';
        $this->OK($msg);
    }
}
